package com.example.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.example.common.constants.WeChatConstants;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: yoonada
 * @email: m15602498163@163.com
 * @create: 2020-10-28 13:53
 * @description: 微信小程序工具类
 */
public class WeChatUtil {

    /**
     * 请求微信后台获取用户数据
     * @param appId
     * @param secret
     * @param code
     * @param grantType
     * @return
     * @throws Exception
     */
    public static String jsCode2Session(String appId,String secret,String code,String grantType)throws Exception{
        //定义返回的json对象
        JSONObject result = new JSONObject();
        //创建请求通过code换取session等数据
        HttpPost httpPost = new HttpPost(WeChatConstants.JS_CODE_2_SESSION);
        List<NameValuePair> params=new ArrayList<>();
        //建立一个NameValuePair数组，用于存储欲传送的参数
        params.add(new BasicNameValuePair("appid",appId));
        params.add(new BasicNameValuePair("secret",secret));
        params.add(new BasicNameValuePair("js_code",code));
        params.add(new BasicNameValuePair("grant_type",grantType));
        //设置编码
        httpPost.setEntity(new UrlEncodedFormEntity(params));
        return EntityUtils.toString(new DefaultHttpClient().execute(httpPost).getEntity());
    }


}
